/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.modules.search.meilishuo;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Logger;
import com.koorz.modules.crawl.CrawlHistory;
import com.koorz.modules.image.Image;
import com.koorz.modules.search.SimpleHttpClient;
import com.koorz.modules.search.TaskService;
import com.koorz.modules.search.ThreadPoolMananger;
import com.koorz.modules.search.UrlWrapper;
import com.koorz.modules.user.User;
import com.koorz.utils.DateUtil;

/**
 * 功能描述：获取导航页数据任务
 * 作        者：尹东东 
 * 创建时间：2013-5-27 下午3:58:21
 * 版  本  号：1.0
 */
public class NaviTask implements Runnable{
	protected final Logger logger = Logger.getLogger(getClass());
	
	@Override
	public void run() {
		SimpleHttpClient client = new SimpleHttpClient();
		TaskService taskService = TaskService.getInstance();
		MeilishuoParser parser = MeilishuoParser.getInstance();
		while (true) {
			UrlWrapper navi = parser.getNavi();
			if(navi != null){
				String result = client.get(navi.getUrl(),parser.getCookie());
				if(StringUtils.isEmpty(result)){
					continue;
				}
				JSONArray jsonArray = null;
				try {
					JSONObject json = JSON.parseObject(result);
					jsonArray = json.getJSONArray("tInfo");
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("NaviTask 获取导航数据失败！"+navi.getUrl(), e);
					continue;
				}
				if(jsonArray != null){
					
					for(int i=0;i<jsonArray.size();i++){
						JSONObject content = jsonArray.getJSONObject(i);
						//保存用户
						JSONObject userJson = content.getJSONObject("uinfo");
						User user = new User();
						user.set("nickname", userJson.getString("nickname"));
						user.set("gender", User.Gender.UNKNOWN.ordinal());
						user.set("avatar_large", userJson.getString("avatar_c"));
						user.set("avatar", userJson.getString("avatar_c"));
						user.set("score", "0");
						user.set("online", "0");
						user = taskService.saveUser(user);
						
						///下载用户头像
						try {
							CrawlHistory crawl = CrawlHistory.dao.findFirst("select * from crawl_history where url=?", userJson.getString("avatar_c"));
							if(crawl == null){
								parser.pushQueue();
								ThreadPoolMananger.ImageQueue.put(user);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
							logger.error("StyleTask 添加图片队列--user 失败！", e);
						}
						//保存主图
						JSONObject imageJson = content.getJSONObject("ginfo");
						Image image = new Image();
						image.set("description", imageJson.getString("goods_title"));
						image.set("url", imageJson.getString("goods_pic_url"));
						image.set("check_state", Image.ImageState.SHOW.ordinal());
						image.set("check_time", DateUtil.getNowDateTime());
						image.set("type", Image.ImageType.SINGLE.ordinal());
						image.set("source_id", imageJson.getString("goods_id"));
						image.set("user_id", user.getStr("id"));
						image.set("source", "meilishuo");
						try {
							image.set("price", Double.parseDouble(imageJson.getString("goods_price").substring(1)));
						} catch (Exception e) {
							logger.error("price获取失败："+imageJson.getString("goods_price"), e);
							image.set("price", 0.0);
						}
						
						image.set("goods_link", content.getString("url"));
						image = taskService.saveImage(image);
						
						taskService.addImageToCategory(image.getStr("id"), navi.getCategoryId());
						taskService.addImageToLabel(image.getStr("id"), navi.getLabel());
						taskService.addImageToLabelGroup(image.getStr("id"), navi.getLabelGroupId());
						
						///下载主图图片
						try {
							CrawlHistory crawl = CrawlHistory.dao.findFirst("select * from crawl_history where url=?", imageJson.getString("goods_pic_url"));
							if(crawl == null){
								parser.pushQueue();
								ThreadPoolMananger.ImageQueue.put(image);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
							logger.error("NaviTask 添加图片队列--image 失败！", e);
						}
					}
				}else {
					continue;
				}
			}
			if(parser.isStopCrawl()){
				logger.debug("NaviTask 导航链接抓取完成");
				break;
			}
		}
		client.close();
	}

}
